#!/usr/bin/env node
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const PROJECT_ROOT = path.join(__dirname, '..')

// 保护名单 - 关键文件和目录
const PROTECTED_FILES = [
  'package.json',
  'package-lock.json',
  'tsconfig.json',
  'jest.config.ts',
  'Dockerfile',
  '.env.example',
  'README.md',
  'LICENSE',
  'CHANGELOG.md',
  'CONTRIBUTING.md'
]

const PROTECTED_DIRS = [
  'src',
  'test',
  'proto',
  'docs',
  'scripts',
  'compatibility-layer',
  'wasm'
]

// 可清理目录及其保留策略
const CLEANABLE_DIRS = {
  'logs': { keepLast: 5 }, // 保留最近5个日志文件
  'coverage': { keep: false },
  'dist': { keep: false },
  'node_modules': { keep: false },
  '.vscode': { keep: false },
  'src/**/*.js': { 
    keep: false,
    exclude: [
      'src/core/intelligent-compat.js',
      'src/core/NetworkAdapter.js',
      'src/compatibility/AIEngineRouter.js',
      'src/compatibility/TextProcessor.js'
    ]
  },
  'src/**/*.js.map': {
    keep: false,
    exclude: [
      'src/core/intelligent-compat.js.map',
      'src/core/NetworkAdapter.js.map',
      'src/compatibility/AIEngineRouter.js.map',
      'src/compatibility/TextProcessor.js.map'
    ]
  }
}

// 主清理函数
async function cleanup() {
  console.log('Starting compatibility engine cleanup...')
  
  // 清理可清理目录
  for (const [dir, strategy] of Object.entries(CLEANABLE_DIRS)) {
    const dirPath = path.join(PROJECT_ROOT, dir)
    if (!fs.existsSync(dirPath)) continue

    if (strategy.keepLast) {
      await cleanWithRetention(dirPath, strategy.keepLast)
    } else {
      console.log(`Cleaning directory: ${dir}`)
      fs.rmSync(dirPath, { recursive: true, force: true })
    }
  }

  // 清理临时文件
  cleanTempFiles()

  console.log('Cleanup completed successfully!')
}

// 保留最近N个文件的清理
async function cleanWithRetention(dirPath, keepLast) {
  const files = fs.readdirSync(dirPath)
    .map(file => ({
      name: file,
      time: fs.statSync(path.join(dirPath, file)).mtime.getTime()
    }))
    .sort((a, b) => b.time - a.time)

  const filesToDelete = files.slice(keepLast)
  for (const file of filesToDelete) {
    const fullPath = path.join(dirPath, file.name)
    console.log(`Deleting old file: ${file.name}`)
    fs.rmSync(fullPath, { recursive: true, force: true })
  }
}

// 清理各种临时文件
function cleanTempFiles() {
  const tempPatterns = [
    '*.log',
    '*.tmp',
    '*.temp',
    '*.bak',
    '*.map',
    '*.tsbuildinfo'
  ]

  const cleanFiles = []
  fs.readdirSync(PROJECT_ROOT).forEach(file => {
    if (PROTECTED_FILES.includes(file)) return
    if (tempPatterns.some(pattern => file.endsWith(pattern.slice(1)))) {
      cleanFiles.push(file)
    }
  })

  for (const file of cleanFiles) {
    console.log(`Deleting temporary file: ${file}`)
    fs.unlinkSync(path.join(PROJECT_ROOT, file))
  }
}

// 执行清理
cleanup().catch(err => {
  console.error('Cleanup failed:', err)
  process.exit(1)
})